<?php
/*
2016-11-22 吴俊源
供货商模块，支持lbs定位搜索
前端请使用百度坐标传参
*/
class SupplierAction extends CommonAction {
	function index(){
		//默认2000米搜索范围
		$raidus = 50000;
		//默认分页大小10条/页
        $pagesize = 10;
		//如果用户指定分页大小，则使用用户指定的数量进行分页
        if ($this->_get('pagesize')) {
            $pagesize = intval($this->_get('pagesize'));
        }
		//指定搜索距离（单位是米）
		if($this->_get('raidus')){
			$raidus = $this->_get('raidus');
		}
		//默认情况下，读取当前站点数据，指定site_id
        $listmap = 's.type = 2 and s.status = 1 and s.site_id = '.__SITEID__;
		//实例化供货商表模型，以便进行数据读取
        $supplierDB = D('Supplier');
		//是否有搜索关键词提交上来
		if(isset($_GET['keywords'])){
			//用户可以通过店名搜索到记录
			$listmap .= " and shopname like '%".($_GET['keywords'])."%'";
		}
		
		$field = '';
		//用户提交百度坐标查询 
		if($this -> _get('Point')){
			$Point = explode(',', $this->_get('Point'));
			//将百度坐标转换成经纬度
			//$Point = curlRequest('http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x='.$Point[0].'&y='.$Point[1]);
			//$Point = json_decode($Point, true);
			//计算2000米内当前位置的经纬度范围
			$array = $this->getAround($Point[0], $Point[1], $raidus);
			//产生查询条件
			$listmap .= " and status = 1 and (lx >= ".$array['minLat']." and lx <= ".$array['maxLat'].") and (ly >= ".$array['maxLng']." and ly <= ".$array['minLng'].")";
			//mysql 计算两点距离进行排序
			
			$lng1 = $Point[0];
		    $lat1 = $Point[1];
		    $lng2 = 'baidumapX';
		    $lat2 = 'baidumapY';
			$field = "round(6378.138*2*asin(sqrt(pow(sin( ($lat1*pi()/180-$lat2*pi()/180)/2),2)+cos($lat1*pi()/180)*cos($lat2*pi()/180)* pow(sin( ($lng1*pi()/180-$lng2*pi()/180)/2),2)))*1000) as distance, s.*";
			
			
			//$field = "ROUND(6378.138*2*ASIN(SQRT(POW(SIN((".base64_decode($Point['x'],true)."*PI()/180-lx*PI()/180)/2),2)+COS(22.299439*PI()/180)*COS(lx*PI()/180)*POW(SIN((".base64_decode($Point['y'],true)."*PI()/180-ly*PI()/180)/2),6)))*1000) as distance, s.*";
			//按距离升序
			$order = 'distance asc';
		}
		//计算全部数据个数，以便进行分页
		$count = $supplierDB->alias('s')->where($listmap)->count();
		//引入分类类
        import('ORG.Util.Page');
		//实例化分页类
        $p = new Page($count, $pagesize);
		//开始分页查询
        $list = $supplierDB->alias('s') -> Field($field) ->where($listmap)->limit($p->firstRow . ',' . $p->listRows) -> order($order) -> select();
		//生成分页字符串
		$pages = $p->show();
		//填充数据列表
		$this->assign('list', $list);
		//填充分页字符
		$this->assign('pages', $pages);
		//显示页面
		$this->display();
	}
	
	//计算距离
	private function getDistance($lat1, $lng1, $lat2, $lng2)
	{
		$earthRadius = 6367000; 
		  $lat1 = ($lat1 * pi()) / 180;
		$lng1 = ($lng1 * pi()) / 180;
		$lat2 = ($lat2 * pi()) / 180;
		$lng2 = ($lng2 * pi()) / 180;
		$calcLongitude = $lng2 - $lng1;
		$calcLatitude = $lat2 - $lat1;
		$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
		$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
		$calculatedDistance = $earthRadius * $stepTwo;
		$ret = round($calculatedDistance);
		return $ret;
	}
	
	
	
	public function getAround($latitude,$longitude,$raidus){
        $PI = 3.14159265;
        $degree = (24901*1609)/360;
        $dpmLat = 1/$degree;
        $radiusLat = $dpmLat*$raidus;
        $minLat = $latitude - $radiusLat;
        $maxLat = $latitude + $radiusLat;
        $mpdLng = $degree*cos($latitude * ($PI/180));
        $dpmLng = 1 / $mpdLng;
        $radiusLng = $dpmLng*$raidus;
        $minLng = $longitude - $radiusLng;
        $maxLng = $longitude + $radiusLng;
        return array (minLat=>$minLat, maxLat=>$maxLat, minLng=>$minLng, maxLng=>$maxLng);
    }
	
	
	//店铺评情
	public function shop(){
		
		if(intval($_GET['supplier_id']) == 0){
			$this->error('参数错误！');
			exit();
		}
		$this->dao = M('Supplier');
		
		$supplier_id = $this->_get('supplier_id');
		$map['id'] = $supplier_id;
		$map['site_id'] = __SITEID__;
		$this->supplier = $this->dao -> where($map) -> find();
		$this->display();
		 
	}
	
	
	public function product(){
		
		
		if(intval($_GET['supplier_id']) == 0){
			$this->error('参数错误！');
			exit();
		}
		$pagesize = 10;
		//如果用户指定分页大小，则使用用户指定的数量进行分页
        if ($this->_get('pagesize')) {
            $pagesize = intval($this->_get('pagesize'));
        }
		$productdb = D('Product'); 
		
		$listmap = 1;
		$listmap .= " and site_id = ".__SITEID__. " and status = 1 and supplier_id = ".$this->_get('supplier_id');
		
		$count = $productdb->where($listmap)->count();
		//引入分类类
        import('ORG.Util.Page');
		//实例化分页类
        $p = new Page($count, $pagesize);
		//开始分页查询
        $list = $productdb -> Field($field) ->where($listmap)->limit($p->firstRow . ',' . $p->listRows) -> order($order) -> select();
		//生成分页字符串
		$pages = $p->show();
		//填充数据列表
		$this->assign('list', $list);
		//填充分页字符
		$this->assign('pages', $pages);
		//显示页面
		$this->display();
	}
	
	
	//重写显示页面方法，迎合前端实现ajax数据传输
	public function display($temp = ''){
		$map  = "site_id = ".__SITEID__." and groupname = '".strtolower(GROUP_NAME)."' and (modelname = '".strtolower(MODULE_NAME)."' or modelname = '*') and (actionname = '".strtolower(ACTION_NAME)."' or actionname = '*')";
		$Systempages = M('Systempages') -> where($map) -> find();
		if(IS_AJAX){
			
			$html = '';
			if($Systempages){
				$ModulesDB = D('Modules');
				$this->initView();
				$this->getModulesByID($this->view, $ModulesDB);
				$html .= $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-header.html');
				$html .= $ModulesDB->getListToString($Systempages['page_view_id'],$this->view,false,true);
				$html .= $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-footer.html');
			}else{
				$html = $this->fetch($temp);
			}
			$list = $_GET['list'];
			$empty = 1;
			$statu=$list?1:0;
			if($this->get('list')){ 
				$empty = 0;
			}
			$this->initView();
			die(json_encode(array('empty' => $empty,'tbody'=>$html,'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this->view->get('pages'))));
		}else{
			if($Systempages){
				$ModulesDB = D('Modules');
			    $this->initView();
				$this->getModulesByID($this->view, $ModulesDB);
			    $html = $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-header.html');
			    $html .= $ModulesDB->getListToString($Systempages['page_view_id'],$this->view,false,true);
			    $html .= $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-footer.html');
				echo $html;
			}else{
				parent::display($temp);
			}
			
			
		} 
	}
	
}